﻿
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Memory;
using OA.Core;
using OA.Model;
using OA.Web.Attribute;
using OA.Web.Code;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Web;
using OA.Model.DB;
using OA.Core.Helper;
using X.PagedList;
using OA.Core.EF;

namespace OA.Web.Areas.Member.Controllers
{
    public class TestPaperController : BaseMemberController
    {
        private IMemoryCache _cache;
        private ICookie _cookie;
        public TestPaperController(ICookie cookie, IHttpContextAccessor accessor, IMemoryCache cache) : base(accessor, cookie, cache)
        {
            _cache = cache;
            _cookie = cookie;
        }

        [MyActionFilterAttribute("001011", "我的考试", "个人中心", true, "iconshijuan")]
        public IActionResult Index(string keyWord,int p = 1,int size = 12)
        {
            return View();
        }

        [MyActionFilterAttribute("001011", "我的考试")]
        public IActionResult GetData(string keyWord, int page = 1, int limit = 12)
        {
            ViewBag.KeyWord = keyWord;
            Expression<Func<EmployeeTestPaperView, bool>> where = m => m.EmpID == this.EmpID;
            if (!string.IsNullOrWhiteSpace(keyWord))
            {
                where = where.AndAlso<EmployeeTestPaperView>(m => m.Title.Contains(keyWord));
            }
            var list = this.dbContextFactory.DbContext.EmployeeTestPaperView.Where(where).OrderByDescending(m => m.ID).ToPagedList(page, limit);
            var result = new
            {
                code = "0",
                msg = "",
                count = list.TotalItemCount,
                data = list
            };
            return Json(result);

        }


        [MyActionFilterAttribute("001011", "我的考试")]
        public IActionResult Write(int id)
        {
            EmployeeTestPaper infoEmployeeTestPaper=this.dbContextFactory.DbContext.EmployeeTestPaper.Where(m => m.ID == id).FirstOrDefault();

            if (infoEmployeeTestPaper == null || infoEmployeeTestPaper.EmpID != this.EmpID)
            {
                return Redirect($"/Member/TestPaper/Index?msg=没有找到该试卷");
            }

            if (infoEmployeeTestPaper.FillingDate != null)
            {
                return Redirect($"/Member/TestPaper/Show/{id}");
            }
            TestPaper infoTestPaper = this.GetInfo<TestPaper>(infoEmployeeTestPaper.TestPaperID);
            List<EmployeeTestPaperSelect> listResult = this.dbContextFactory.DbContext.EmployeeTestPaperSelect.Where(m => m.TestPaperID == infoTestPaper.ID && m.EmpID == Info.EmpID).ToList();
            ViewBag.TestPaper = infoTestPaper;
            List<TestPaperItem> items = new List<TestPaperItem>();
            if (!string.IsNullOrWhiteSpace(infoTestPaper.ExamTopicContent))
            {
                items = JsonHelper.DeserializeList<TestPaperItem>(infoTestPaper.ExamTopicContent);
            }
            if (items == null || items.Count == 0)
            {
                items = new List<TestPaperItem>() { new TestPaperItem() { } };
            }
            ViewBag.Result = listResult;
            return View(items);

        }

        [HttpPost]
        [MyActionFilterAttribute("001011", "我的考试")]
        public IActionResult Write(int id, List<EmployeeTestPaperSelect> MyItems)
        {
            EmployeeTestPaper infoEmployeeTestPaper = this.dbContextFactory.DbContext.EmployeeTestPaper.Where(m => m.ID == id).FirstOrDefault();

            if (infoEmployeeTestPaper == null || infoEmployeeTestPaper.EmpID != this.EmpID)
            {
                return Redirect($"/Member/TestPaper/Index?msg=没有找到该试卷");
            }

            if (infoEmployeeTestPaper.FillingDate != null)
            {
                return Redirect($"/Member/TestPaper/Show/{id}");
            }
            TestPaper infoTestPaper = this.GetInfo<TestPaper>(infoEmployeeTestPaper.TestPaperID);
            List<EmployeeTestPaperSelect> listResult = this.dbContextFactory.DbContext.EmployeeTestPaperSelect.Where(m => m.TestPaperID == infoTestPaper.ID && m.EmpID == Info.EmpID).ToList();
            ViewBag.TestPaper = infoTestPaper;
            List<TestPaperItem> items = new List<TestPaperItem>();
            if (!string.IsNullOrWhiteSpace(infoTestPaper.ExamTopicContent))
            {
                items = JsonHelper.DeserializeList<TestPaperItem>(infoTestPaper.ExamTopicContent);
            }
            if (items == null || items.Count == 0)
            {
                items = new List<TestPaperItem>() { new TestPaperItem() { } };
            }
            if (items.Count != MyItems.Count)
            {
                return Redirect($"/Member/TestPaper/Write?id={id}&msg=错误格式不正确");
            }

            var question = items.Select(m => m.ID).ToList();
            var answer = MyItems.Select(m => m.TestPaperItemID).ToList();
            if (question.Except(answer).Count() > 0)//判断是否又差集
            {
                //.... 答案与问题不匹配
                return Redirect($"/Member/TestPaper/Write?id={id}&msg=错误格式不正确");
            }

            List<EmployeeTestPaperSelect> addItem = new List<EmployeeTestPaperSelect>();
            List<EmployeeTestPaperSelect> updateItems = new List<EmployeeTestPaperSelect>();
            decimal score = 0;
            foreach (EmployeeTestPaperSelect item in MyItems)
            {
                TestPaperItem itemTestPaper = items.Where(m => m.ID == item.TestPaperItemID).FirstOrDefault();
                if(itemTestPaper==null|| itemTestPaper.Type!=item.Type)
                {
                    //.... 答案与问题不匹配
                    return Redirect($"/Member/TestPaper/Write?id={id}&msg=错误格式不正确");
                }
                item.Options = string.Join(",", item.MyOptions);
                var myItem= listResult.Where(m => m.TestPaperItemID == item.TestPaperItemID).FirstOrDefault();
                if (myItem == null)
                {
                    item.CreateDateTime = DateTime.Now;
                    item.EmpID = Info.EmpID;
                    item.Status = 1;
                    item.TestPaperID = infoTestPaper.ID;
                    addItem.Add(item);
                }
                else if (myItem.Options != item.Options)
                {
                    updateItems.Add(item);
                }
                if (!string.IsNullOrWhiteSpace(item.Options))
                {
                    item.Options = item.Options.Replace(",", "");
                }
                if(item.Options== itemTestPaper.Answer)
                {
                    score += itemTestPaper.Score;
                }
                else if(item.Type==2&& !string.IsNullOrWhiteSpace(item.Options)&&!string.IsNullOrWhiteSpace(itemTestPaper.Answer))//多选，选对部分得一半分
                {
                    char[] temp = item.Options.Replace(",", "").Replace("，", "").ToCharArray();
                    char[] temp2 = itemTestPaper.Answer.Replace(",", "").Replace("，", "").ToCharArray();

                    if(temp2.Intersect(temp).Count()>0&& temp.Except(temp2).Count()==0)
                    {
                        score += itemTestPaper.Score / 2;
                    }

                }
            }

            using (var trn=this.dbContextFactory.DbContext.Database.BeginTransaction())
            {
                try
                {
                    if (addItem.Count > 0)
                    {
                        this.AddRange<EmployeeTestPaperSelect>(addItem);
                    }
                    if (updateItems.Count > 0)
                    {
                        foreach (EmployeeTestPaperSelect updateItem in updateItems)
                        {
                            EmployeeTestPaperSelect item = listResult.Where(m => m.TestPaperItemID == updateItem.TestPaperItemID).FirstOrDefault();
                            this.Update<EmployeeTestPaperSelect>(item, updateItem, new string[] { "Options" });

                        }
                    }

                    EmployeeTestPaper updateEmployeeTestPaper = new EmployeeTestPaper();
                    updateEmployeeTestPaper.Status = 1;
                    updateEmployeeTestPaper.FillingDate = DateTime.Now;
                    updateEmployeeTestPaper.Score = score;
                    this.Update<EmployeeTestPaper>(infoEmployeeTestPaper, updateEmployeeTestPaper, new string[] { "Status", "FillingDate", "Score" });
                    trn.Commit();
                    return Redirect($"/Member/TestPaper/Show/{id}");
                }
                catch(Exception ex)
                {
                    trn.Rollback();
                    ViewBag.Result = MyItems;
                    return View(items);
                }                
            }
        }
        [MyActionFilterAttribute("001011", "我的试卷")]
        public IActionResult Show(int id)
        {
            EmployeeTestPaper infoEmployeeTestPaper = this.dbContextFactory.DbContext.EmployeeTestPaper.Where(m => m.ID == id).FirstOrDefault();
            if (infoEmployeeTestPaper == null || infoEmployeeTestPaper.EmpID != this.EmpID)
            {
                return Redirect($"/Member/TestPaper/Index?msg=没有找到该试卷");
            }
            TestPaper infoTestPaper = this.GetInfo<TestPaper>(infoEmployeeTestPaper.TestPaperID);
            List<EmployeeTestPaperSelect> listResult = this.dbContextFactory.DbContext.EmployeeTestPaperSelect.Where(m => m.TestPaperID == infoTestPaper.ID && m.EmpID == Info.EmpID).ToList();
            ViewBag.TestPaper = infoTestPaper;
            List<TestPaperItem> items = new List<TestPaperItem>();
            if (!string.IsNullOrWhiteSpace(infoTestPaper.ExamTopicContent))
            {
                items = JsonHelper.DeserializeList<TestPaperItem>(infoTestPaper.ExamTopicContent);
            }
            if (items == null || items.Count == 0)
            {
                items = new List<TestPaperItem>() { new TestPaperItem() { } };
            }
            ViewBag.Result = listResult;
            return View(items);

        }

    }
}